package com.ytktt.study.week3.task346.gateway.config;

import com.ytktt.study.week3.task346.gateway.properties.HttpClientProperties;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Http Client配置
 *
 * @author ytk
 */
@Configuration
@EnableConfigurationProperties(HttpClientProperties.class)
public class HttpClientConfig {

    @Bean
    public CloseableHttpAsyncClient closeableHttpAsyncClient(HttpClientProperties httpClientProperties) {
        int cores = Runtime.getRuntime().availableProcessors() + 2;
        IOReactorConfig ioConfig = IOReactorConfig.custom()
                .setConnectTimeout(httpClientProperties.getConnectTimeout())
                .setSoTimeout(httpClientProperties.getSoTimeout())
                .setIoThreadCount(httpClientProperties.getIoThreadCount() == 0 ? cores : httpClientProperties.getIoThreadCount())
                .setRcvBufSize(httpClientProperties.getRcvBufferSize() * 1024)
                .build();

        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setMaxConnTotal(httpClientProperties.getMaxConnTotal())
                .setMaxConnPerRoute(httpClientProperties.getMaxConnPerRoute())
                .setDefaultIOReactorConfig(ioConfig)
                .setKeepAliveStrategy((response, context) -> httpClientProperties.getKeepaliveTime())
                .build();
        httpclient.start();
        return httpclient;
    }
}
